/*
   UIPEthernet TCPServer example.

   UIPEthernet is a TCP/IP stack that can be used with a enc28j60 based
   Ethernet-shield.

   UIPEthernet uses the fine uIP stack by Adam Dunkels <adam@sics.se>

        -----------------

*/

#define MACADDRESS 0x00,0x01,0x02,0x03,0x04,0x05 //MAC 地址
#define MYIPADDR 192,168,4,6 //修改你的ip
#define MYIPMASK 255,255,255,0
#define MYDNS 192,168,4,4 //修改你的dns
#define MYGW 192,168,4,4//修改你的网关
#define LISTENPORT 1000//修改你的TCP端口
#define UARTBAUD 115200


#include <UIPEthernet.h>

EthernetServer server = EthernetServer(LISTENPORT);

void setup() {
  Serial.begin(UARTBAUD);
  uint8_t mac[6] = {MACADDRESS};
  uint8_t myIP[4] = {MYIPADDR};
  uint8_t myMASK[4] = {MYIPMASK};
  uint8_t myDNS[4] = {MYDNS};
  uint8_t myGW[4] = {MYGW};

  //  Ethernet.begin(mac,myIP);
  Ethernet.begin(mac, myIP, myDNS, myGW, myMASK);

  server.begin();
}
String client_text = ""; //客户端发过来的字串
bool go_client = false; //客户端判断数据

bool wait_serial = false; //串口判断
String serial_text = ""; //串口发过来的字串
bool go_serial = false; //串口判断数据

void loop() {
  EthernetClient client = server.available();
  if (client)
  {
    while (client.connected()) { //如果tcp有连接到

      while ( client.available() > 0) { //如果有数据
        char c = client.read();
        if (c == '\n') {
          go_client = true;
        }
        else {
          client_text += c;
        }
        if (go_client == true) { //客户端请求

          Serial.println(client_text );//转发到串口
          //开始串口请求
          wait_serial = true;
          int times_s = 0;
          while ( wait_serial) {
            if ( times_s < 2000) {
              while ( Serial.available() > 0) { //如果有数据
                char c = Serial.read();
                if (c == '\n') {
                  go_serial = true;
                }
                else {
                  serial_text += c;
                }
                if (go_serial == true) {

                  client.println(serial_text );//转发到串口
                  go_serial = false;
                  wait_serial =  false;
                  serial_text = "";
                  break;

                }
              }
              delay(1); //延时1ms
              times_s ++; //累加
            }
            else {
              if (wait_serial == true) {
                client.println("error");//串口超时反馈客户端
                wait_serial = false;
              }
            }

          }
          //结束串口请求
          go_client = false;
          client_text = "";
        }
      }
      client.stop();
    }
  }
}

